package com.example.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.dto.LoginDto;
import com.example.entity.User;
import com.example.entity.dto.PasswordReqDto;
import com.example.entity.vo.UserVo;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 基础前端接口
 */
@RestController
public class WebController {

    @Resource
    private UserService userService;

    @GetMapping("/")
    public Result hello() {
        return Result.success("访问成功");
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        if (ObjectUtil.isEmpty(loginDto.getUsername()) || ObjectUtil.isEmpty(loginDto.getPassword())) {
            return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        UserVo userVo = userService.login(loginDto);
        return Result.success(userVo);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody PasswordReqDto passwordReqDto) {
        userService.updatePassword(passwordReqDto);
        return Result.success();
    }

    /**
     * 退出登录
     * @return Result
     */
    @GetMapping("/logout")
    public Result logout() {
        String loginId = StpUtil.getLoginId().toString();
        // 退出登录
        StpUtil.logout(loginId);
        return Result.success();
    }

}
